package com.googlecode.derby.customize.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.googlecode.derby.customize.SqlMaker;

/**
 * 例外処理.
 *
 * @author o.tanaka
 * @version 2009/12/11
 */
public class SqlMakerException extends RuntimeException {

    private static final long serialVersionUID = 3256727285930210360L;

    private final String stackTrace;

    /**
     * 例外処理.
     *
     * @param message
     *            String
     * @param sqlMaker
     *            SqlMaker
     * @param e
     *            Throwable
     */
    public SqlMakerException(
            final String message,
            final SqlMaker sqlMaker,
            final Throwable e) {
        super(message);
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        super.initCause(e);
        super.printStackTrace(pw);
        final String query = sqlMaker.getQuery();
        if (query != null) {
            pw.println(new StringBuilder("\nINFO:").toString());
            pw.println(new StringBuilder("\tquery -->")
                    .append(query).toString());
        }
        this.stackTrace = sw.toString();
    }

    /**
     * @param message
     *            message
     * @param e
     *            Throwable
     */
    public SqlMakerException(
            final String message, final Throwable e) {
        super(message);
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        super.initCause(e);
        super.printStackTrace(pw);
        this.stackTrace = sw.toString();

    }

    /**
     * @see java.lang.Throwable#printStackTrace()
     */
    @Override
    public final void printStackTrace() {
      this.printStackTrace(System.err);
    }
    /**
     * @see java.lang.Throwable#printStackTrace(java.io.PrintStream)
     * @param s PrintStream
     */
    @Override
    public final void printStackTrace(final java.io.PrintStream s) {
      synchronized (s) {
        s.print(this.stackTrace);
      }
    }
    /**
     * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter)
     * @param s PrintWriter
     */
    @Override
    public final void printStackTrace(final java.io.PrintWriter s) {
      synchronized (s) {
        s.print(this.stackTrace);
      }
    }

}
